<template>
  <div>
    <el-dialog title="账户信息" :visible.sync="dialogFormVisible" width="90%">
      <el-card class="box-card" shadow="always">
        <div slot="header" class="clearfix">
          <el-row :gutter="20">
            <el-col :span="5">
              <span>账户编号：{{accountInfo.accountNumber}}</span>
            </el-col>
            <el-col :span="3">
              <span>入住老人：{{accountInfo.elderlyName}}</span>
            </el-col>
            <el-col :span="3">
              <span>入住状态：<el-tag v-if="accountInfo.retreat" type="info">已退住</el-tag>
                <el-tag v-else type="success">入住中</el-tag>
              </span>
            </el-col>
            <el-col :span="7">
              <span>入住时间：{{accountInfo.checkedInTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="5">
              <span>预交金：<el-tag type="success">¥</el-tag>{{accountInfo.advancePayment | money}}</span>
            </el-col>
            <el-col :span="5">
              <span>押  金：<el-tag type="success">¥</el-tag>{{accountInfo.deposit | money}}</span>
            </el-col>
          </el-row>
        </div>
        <div v-if="checkInMark">
          <el-form :inline="true"  class="demo-form-inline">
            <el-button-group v-if="checkInMark">
              <el-button type="primary"  size="small" round @click="rechargeDepositOpen(1)">交押金</el-button>
              <el-button type="primary" size="small" round @click="rechargeDepositOpen(2)">充值预交金</el-button>
              <el-button type="warning" size="small" round @click="rechargeDepositOpen(-1)">退押金</el-button>
              <el-button type="warning" size="small" round @click="rechargeDepositOpen(-2)">退预交金</el-button>
            </el-button-group>
            <el-row>
              <el-col :span="24">
                <el-tabs type="border-card" @tab-click="handleClick" value="recharge">
                  <el-tab-pane lazy name="recharge">
                    <span slot="label"><i class="el-icon-date"></i> 充值流水</span>
                    <el-form :inline="true"  class="demo-form-inline">
                      <el-form-item label="操作时间">
                        <el-date-picker type="date" v-model="queryinfo.startTime" placeholder="选择开始日期" style="width: 150px"></el-date-picker>
                        -
                        <el-date-picker type="date" v-model="queryinfo.endTime" placeholder="选择结束日期" style="width: 150px"></el-date-picker>
                      </el-form-item>
                      <el-form-item label="操作类型">
                        <el-select v-model="queryinfo.changeType"  placeholder="请选择操作类型">
                          <el-option label="全部" value=""></el-option>
                          <el-option label="充值押金" value="1"></el-option>
                          <el-option label="退押金" value="-1"></el-option>
                          <el-option label="充值预交金" value="2"></el-option>
                          <el-option label="退预交金" value="-2"></el-option>
                          <el-option label="预交金消费" value="999"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="searchFeeDetailsOfAccount">查询</el-button>
                      </el-form-item>
                    </el-form>
                    <el-table
                      :data="feedetail"
                      height="350"
                      :loading="feedetailloading"
                      border
                      style="width: 100%">
                      <el-table-column
                        prop="operateTime"
                        align="center"
                        label="日期"

                        width="300">
                        <template slot-scope="scope">
                          {{scope.row.operateTime| parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="changeType"
                        align="center"
                        label="操作"
                        width="250">
                        <template slot-scope="scope">
                          <span v-if="scope.row.changeType == 1">充值押金</span>
                          <span v-if="scope.row.changeType == -1">退押金</span>
                          <span v-if="scope.row.changeType == 2">充值预交金</span>
                          <span v-if="scope.row.changeType == -2">退预交金</span>
                          <span v-if="scope.row.changeType == 999">预交金消费</span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="amount"
                        align="center"
                        width="150"
                        label="金额（¥）">
                      </el-table-column>
                      <el-table-column
                        prop="feeReason"
                        header-align="center"
                        label="备注">
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                  <el-tab-pane lazy name="monthfee">
                    <span slot="label"><i class="el-icon-help"></i> 基础月费</span>
                    <el-button icon="el-icon-plus" type="primary"  @click="addMonthFee">
                      添加月费
                    </el-button>
                    <el-button icon="el-icon-refresh" circle style="float: right; "  @click="searchBasicMonthlyFee"></el-button>
                    <el-table
                      :data="monthlyFeedetail"
                      height="350"
                      :loading="monthlyFeedetailloading"
                      border
                      style="width: 100%">
                      <el-table-column
                        prop="itemName"
                        align="center"
                        label="项目名称"
                        min-width="300">
                      </el-table-column>
                      <el-table-column
                        prop="feeTypeName"
                        align="center"
                        label="类型"
                        min-width="250">
                      </el-table-column>
                      <el-table-column
                        align="center"
                        min-width="150"
                        label="月费用（¥）">

                        <template slot-scope="scope">{{ parseFloat(scope.row.monthFee).toFixed(2)}}</template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        min-width="150"

                        label="日费用（¥）">
                        <template slot-scope="scope">{{ parseFloat(scope.row.dailyFee).toFixed(2)}}</template>
                      </el-table-column>
<!--                      <el-table-column-->
<!--                        show-overflow-tooltip-->
<!--                        label="操作"-->
<!--                        align="center"-->
<!--                        min-width="150px"-->
<!--                        fixed="right"-->
<!--                      >-->

<!--                        <template slot-scope="scope">-->
<!--                          <el-button type="text"  @click="removeFee(scope.row)">-->
<!--                            删除-->
<!--                          </el-button>-->
<!--                        </template>-->

<!--                      </el-table-column>-->
                    </el-table>
                  </el-tab-pane>
                </el-tabs>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <add_monthfee_dialog ref="addMonthFeeDialog" ></add_monthfee_dialog>
      </el-card>
    </el-dialog>
    <el-dialog :title="accountHandle.name" :visible.sync="accountHandleDialogVisible">
      <el-form >
        <el-form-item label="金额" label-width="120px">
          <el-input type="number" v-model="accountHandle.amount" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="accountHandleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rechargeDepositEvent">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {searchElderlyFilesOfCondition} from "@/api/elderly"
  import {searchCheckInInfoOfElderly} from "@/api/checkin"
  import {searchAccountDetail, rechargeDeposit, rechargeAdvancePayment,
    refundDeposit, refundAdvancePayment, searchFeeDetails, searchBasicMonthlyFees, removeBasicMonthlyFee} from "@/api/account"
  import AddMonthFee from "./AddMonthFee"
  import { parseTime} from "@/utils/index";
  import Template from "../../../nursing/template";
  export default {
    name: "",
    components: {
        Template,
      "add_monthfee_dialog": AddMonthFee
    },
    filters: {
      parseTime: parseTime,
      money(val)
      {
        val = (val+"").replace(/\$|\,/g, "");
        if (isNaN(val))
        {
          val = "0";
        }
        let sign = (val == (val = Math.abs(val)));
        val = Math.floor(val * 100 + 0.50000000001);
        let cents = val % 100;
        val = Math.floor(val / 100).toString();
        if (cents < 10)
        {
          cents = "0" + cents;
        }
        for (let i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++)
        {
          val = val.substring(0, val.length - (4 * i + 3)) + "," + val.substring(val.length - (4 * i + 3));
        }

        return (((sign) ? "" : "-") + val + "." + cents);
      }
    },
    data() {
      return {
        checkInMark: undefined,
        dialogFormVisible: false,
        accountInfo: {
          "accountNumber": undefined,
          "advancePayment": undefined,
          "checkInMark": undefined,
          "checkInType": undefined,
          "checkedInTime": undefined,
          "createTime": undefined,
          "creator": undefined,
          "del": undefined,
          "deposit": undefined,
          "elderlyCode": undefined,
          "elderlyName": undefined,
          "id": undefined,
          "lastUpdateTime": undefined,
          "lastUpdator": undefined,
          "retreat": undefined,
          "version": undefined
        },
        feedetail: [],
        queryinfo: {
          startTime: '',
          endTime: '',
          changeType: ''
        },
        feedetailloading: false,
        options: [],
        loading: false,
        accountHandleDialogVisible: false,
        accountHandle: {
          name: undefined,
          type: undefined,
          amount: undefined
        },
        monthlyFeedetail: [],
        monthlyFeedetailloading: false
      }
    },
    methods: {
      show(checkInInfo){
        this.checkInMark = checkInInfo.checkInMark
        this.searchAccount()
        this.dialogFormVisible = true
        console.log(checkInInfo)
      },
      async remoteMethod(query) {
        if (query !== '' && query.length>=2) {
          this.loading = true;
          this.options = [];
          let elderlyRes = await searchElderlyFilesOfCondition(query)
          if(elderlyRes.code == '200' && elderlyRes.data){
            for(let i=0; i<elderlyRes.data.length; i++){
              let checkinRes = await searchCheckInInfoOfElderly(elderlyRes.data[i].elderlyCode)
              if(checkinRes.code=='200' && checkinRes.data){
                for(let j=0; j<checkinRes.data.length; j++){
                  this.options.push({
                    checkin: checkinRes.data[j],
                    elderly: elderlyRes.data[i]
                  })
                }
                this.loading = false
              }else{
                this.loading = false
              }
            }
          }else{
            this.loading = false
          }

        } else {
          this.loading = false;
          this.options = [];
        }
      },
      async searchAccount(){
        this.accountInfo = {
          "accountNumber": undefined,
          "advancePayment": undefined,
          "checkInMark": undefined,
          "checkInType": undefined,
          "checkedInTime": undefined,
          "createTime": undefined,
          "creator": undefined,
          "del": undefined,
          "deposit": undefined,
          "elderlyCode": undefined,
          "elderlyName": undefined,
          "id": undefined,
          "lastUpdateTime": undefined,
          "lastUpdator": undefined,
          "retreat": undefined,
          "version": undefined
        }
        if(!this.checkInMark){
          this.clearData()
          return false
        }
        let accountRes = await searchAccountDetail(this.checkInMark)
        if(accountRes.code == '200' && accountRes.data){
          this.accountInfo = accountRes.data
        }else{
          return false
        }
      },
      clearData(){
        this.accountInfo = {
          "accountNumber": undefined,
          "advancePayment": undefined,
          "checkInMark": undefined,
          "checkInType": undefined,
          "checkedInTime": undefined,
          "createTime": undefined,
          "creator": undefined,
          "del": undefined,
          "deposit": undefined,
          "elderlyCode": undefined,
          "elderlyName": undefined,
          "id": undefined,
          "lastUpdateTime": undefined,
          "lastUpdator": undefined,
          "retreat": undefined,
          "version": undefined
        }
        this.feedetail = []
        this.queryinfo = {
          startTime: '',
          endTime: '',
          feeChangeType: ''
        }
        this.options = []
        this.loading = false
      },
      async rechargeDepositEvent(){
        if(this.accountInfo && this.accountInfo.accountNumber){
          if(this.accountHandle.amount <= 0){
            this.$baseMessage("金额不能小于等于0")
            return false
          }
          let data = {
            accountNumber: this.accountInfo.accountNumber,
            money: this.accountHandle.amount
          }
          let handleRes = null
          if(this.accountHandle.type == 1){
            handleRes = await rechargeDeposit(data)
          }else if(this.accountHandle.type == -1){
            handleRes = await refundDeposit(data)
          }else if(this.accountHandle.type == 2){
            handleRes = await rechargeAdvancePayment(data)
          }else if(this.accountHandle.type == -2){
            handleRes = await refundAdvancePayment(data)
          }else{
            this.$baseMessage("操作类型错误")
            return false
          }
          if(handleRes && handleRes.code == '200'){
            this.$baseMessage("操作成功")
            this.accountHandleDialogVisible = false
            this.searchAccount()
          }else{
            this.$baseMessage("操作失败，"+handleRes.message)
          }
        }else{
          this.$baseMessage("请选择入住账户")
        }
      },
      rechargeDepositOpen(type){
        this.accountHandle.type = type
        this.accountHandle.amount=undefined
        if(type == 1){

          this.accountHandle.name = '押金充值'
        }else if(type == -1){
          this.accountHandle.name = '退押金'
        }else if(type == 2){
          this.accountHandle.name = '预交金充值'
        }else if(type == -2){
          this.accountHandle.name = '退预交金'
        }
        this.accountHandleDialogVisible = true
      },
      async searchFeeDetailsOfAccount(){
        if(this.accountInfo && this.accountInfo.accountNumber){
          this.feedetailloading = true
          let detailRes = await searchFeeDetails(this.accountInfo.accountNumber, this.queryinfo)
          if(detailRes.code == '200'){
            this.feedetail = detailRes.data
            this.feedetailloading = false
          }else{
            this.feedetail = []
            this.feedetailloading = false
            this.$baseMessage("查询失败，"+detailRes.message)
          }
        }else{
          this.$baseMessage("请选择入住账户")
          this.feedetail = []
        }
      },
      async searchBasicMonthlyFee(){
        if(this.accountInfo && this.accountInfo.accountNumber){
          let monthlyFeeRes = await searchBasicMonthlyFees(this.accountInfo.checkInMark)
          if(monthlyFeeRes.code == '200'){
            this.monthlyFeedetail = monthlyFeeRes.data
            this.monthlyFeedetailloading = false
          }else{
            this.monthlyFeedetail = []
            this.monthlyFeedetailloading = false
            this.$baseMessage("查询失败，"+monthlyFeeRes.message)
          }
        }else{
          this.$baseMessage("请选择入住账户")
          this.feedetail = []
        }
      },
      addMonthFee(){
        if(this.accountInfo && this.accountInfo.accountNumber){
          this.$refs["addMonthFeeDialog"].show(this.accountInfo.checkInMark);
        }else{
          this.$baseMessage("请选择入住账户")
          this.feedetail = []
        }
      },
      handleClick(tab, event){
        if(tab.name == 'monthfee'){
          this.searchBasicMonthlyFee()
        }else if(tab.name == 'recharge'){
          this.searchFeeDetailsOfAccount()
        }
      },
      removeFee(row){
        this.$confirm('此操作将永久删除该基础月费, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          removeBasicMonthlyFee(row.mark).then(result => {
            if(result.code=='200'){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.searchBasicMonthlyFee()
            }else{
              this.$message.error('删除失败，'+result.message);
            }
          })
        }).catch(() => {

        });
      }
    }
  }
</script>

<style scoped>
  .box-card >>> .el-input__inner {
    border-top-width: 0px;
    border-left-width: 0px;
    border-right-width: 0px;
    border-bottom-width: 1px;
    /*outline: medium;*/
  }
  .el-row {
    margin-bottom: 20px;
  &:last-child {
     margin-bottom: 0;
   }
  }
